package cc.smarnet.caihou.phone.scanin;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import android.device.ScanManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;

import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.client.android.Intents;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.R;

import cc.smarnet.caihou.util.CommonUtils;
import okhttp3.Call;

/**
 * saoma扫码入库
 */
public class ScanInActivity extends Activity {
    private static final String TAG = "ScanInActivity";

    private TextView showTotal;
    private TextView showIds;
    private ImageButton imageButton;
    private Button scanButton;
    private Button sureinButton;
    private String token;
    private String storeHouse;
    private String storeHouseId;
    private String pruID;
    private ArrayList<String> storeHouseList = new ArrayList<>();
    private ArrayList<String> storeHouseIDList = new ArrayList<>();
    private ArrayList<String> pruIDList = new ArrayList<>();
    private  String  pringTagIds = "";
    private Spinner houseSpinner;// 仓库
    private Integer count=0;// 仓库
    private Spinner pruSpinner;//

    String addUrl = "/flower/flowerTagPrint/scanInForPDA";//扫码入库url
    String storeHouseUrl = "/flower/flowerStorehouse/listByPsn";//仓库url

    String getPruIDUrl = "/chvegetable/flowerProduction/list";//批次url

    //扫码dpa相关
    private Vibrator mVibrator;
    private ScanManager mScanManager = null;
    private SoundPool soundpool = null;
    private int soundid;
    private String barcodeStr;
    private boolean isScaning = false;
    private final static String SCAN_ACTION = "urovo.rcv.message";//扫描结束action


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_in);
        initViews();
        getToken();
        getStoreHouse();
        getPruids("");
        showTotal.setText("共："+ count+" ");

        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 点击扫码按钮的监听
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //扫码


                Intent i = new Intent(ScanInActivity.this, ScanActivity.class);

                startActivityForResult(i, 1);
            }
        });
        // 确认入库按钮的监听
        sureinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sureinButton.setEnabled(false);
                sureinButton.setBackgroundColor(Color.GRAY);
                sendDataIn();
            }
        });

        //pda扫码相关
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//        setupView();

    }

    public void initViews() {
        showTotal = findViewById(R.id.show_total);
        showIds = findViewById(R.id.show_ids);
        imageButton = findViewById(R.id.scan_return);
        sureinButton = findViewById(R.id.surein_button);
        scanButton = findViewById(R.id.scan_button);

        houseSpinner = findViewById(R.id.storehouse_spinner);//仓库
        pruSpinner = findViewById(R.id.productID_spinner);//仓库


    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }


    /**
     *  摄像头扫码获取数据
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() == null) {
            Intent originalIntent = result.getOriginalIntent();
            if (originalIntent == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else if (originalIntent.hasExtra(Intents.Scan.MISSING_CAMERA_PERMISSION)) {
                Log.d("MainActivity", "Cancelled scan due to missing camera permission");
                Toast.makeText(this, "Cancelled due to missing camera permission", Toast.LENGTH_LONG).show();
            }
        } else {
//            Log.d("MainActivity", "Scanned");
//            Toast.makeText(this, "扫码成功！: " + result.getContents(), Toast.LENGTH_LONG).show();
            String id = CommonUtils.getIDByUrl(result.getContents());
            if(StringUtils.isBlank(pringTagIds)  ){
                pringTagIds = id;
                count++;
            }else{
                if(pringTagIds.indexOf(id)<0  ){
                    pringTagIds+= ","+ id ;
                    count++;
                }
            }

            String[] dd =  pringTagIds.split(",");
            showIds.setText(pringTagIds.replaceAll(",", "\n")  + "\n" +"\n" + "共：" + count+ "\n" +"\n");
            showTotal.setText("共："+ count+"");
        }
    }


    // 获取仓库下拉
    public void getStoreHouse() {
        String url = IPConfig.baseUrl + storeHouseUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
//                .addParams("name", name)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(ScanInActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonarray = JSON.parseArray(result);
                            storeHouseList.clear();
                            storeHouseIDList.clear();
                            for (int i = 0; i < jsonarray.size(); i++) {
                                JSONObject jsonObj = jsonarray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                String id3 = jsonObj.getString("code");
                                storeHouseList.add(name);
                                storeHouseIDList.add(id3);
                            }
                            if (jsonarray.size() >= 0) {
                                storeHouse = storeHouseList.get(0);// 默认第一个仓库
                                storeHouseId = storeHouseIDList.get(0);
                            } else {
                                storeHouse = "";
                                storeHouseId = "";
                            }
                            houseSpinner();
                        } else {
                            Toast.makeText(ScanInActivity.this, "获取仓库失败" + Boolean.parseBoolean(JSON.parseObject(response).getString("message")), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //仓库下拉
    public void houseSpinner() {
        ArrayAdapter placeArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, storeHouseList);
        placeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        houseSpinner.setAdapter(placeArrayAdapter);
        houseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                storeHouse = storeHouseList.get(i);
                storeHouseId = storeHouseIDList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    // 获取批次下拉
    public void getPruids(String baseid) {
        String url = IPConfig.baseUrl + getPruIDUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("mainid", baseid)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(ScanInActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
                            JSONArray jsonarray = JSON.parseArray(records);
                            pruIDList.clear();
                            for (int i = 0; i < jsonarray.size(); i++) {
                                JSONObject jsonObj = jsonarray.getJSONObject(i);
                                String code = jsonObj.getString("code");
                                pruIDList.add(code);
                            }
                            if (jsonarray.size() >= 0) {
                                pruID = pruIDList.get(0);// 默认第一个仓库
                            } else {
                                pruID = "";
                            }
                            PruidSpinner();
                        } else {
                            Toast.makeText(ScanInActivity.this, "获取批次失败" + Boolean.parseBoolean(JSON.parseObject(response).getString("message")), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //pici下拉
    public void PruidSpinner() {
        ArrayAdapter placeArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, pruIDList);
        placeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        pruSpinner.setAdapter(placeArrayAdapter);
        pruSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                pruID = pruIDList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //提交后台入库
    public void sendDataIn() {
        // 开始调用后台接口进行入库操作。
        //读取   仓库等可选项。
        if (StringUtils.isBlank(storeHouseId)) {
            throw new RuntimeException("请先选择仓库");
        }
        //构建数据，传到后台
        String url = IPConfig.baseUrl + addUrl;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .addParams("storehouse", storeHouseId)
                .addParams("ids",  pringTagIds)
                .addParams("productionId",  pruID)
                .build()
                .connTimeOut(10 * 60 * 1000)
                .readTimeOut(10 * 60 * 1000)
                .writeTimeOut(10 * 60 * 1000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(ScanInActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            Toast.makeText(ScanInActivity.this,   JSON.parseObject(response).getString("message") , Toast.LENGTH_SHORT).show();
//                            CommonUtils.showTotal(ScanInActivity.this,JSON.parseObject(response).getString("message"),R.color.darkseagreen );
                            pringTagIds = "";
                            count = 0 ;
                            showIds.setText(  "\n" +"\n" + "共：" + count+ "\n" +"\n"+ "\n" +"\n");
                            showTotal.setText("共："+ count+" ");
                        } else {
                            Toast.makeText(ScanInActivity.this, "入库失败" +JSON.parseObject(response).getString("message") , Toast.LENGTH_SHORT).show();
                        }
                        sureinButton.setEnabled(true);
                        sureinButton.setBackgroundColor(Color.BLUE);
                    }
                });
    }

    //pda扫码相关
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
//            scanInput.setText("");
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra("barocode");
            //byte[] barcode = intent.getByteArrayExtra("barcode");
            int barocodelen = intent.getIntExtra("length", 0);
            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
            android.util.Log.i("debug", "----codetype--" + temp);
            barcodeStr = new String(barcode, 0, barocodelen);

//            scanInput.setText(barcodeStr);
            String id = CommonUtils.getIDByUrl(barcodeStr);
            if(StringUtils.isBlank(pringTagIds)  ){
                pringTagIds = id;
                count++;
            }else{
                if(pringTagIds.indexOf(id)<0  ){
                    pringTagIds+= ","+ id ;
                    count++;
                }
            }
            String[] dd =  pringTagIds.split(",");
            showIds.setText(pringTagIds.replaceAll(",", "\n")  + "\n" +"\n" + "共：" + count+ "\n" +"\n");
            showTotal.setText("共："+ count+" ");

        }

    };

    private void initScan() {
        // TODO Auto-generated method stub
       try{//兼容手机，没有扫码头
           mScanManager = new ScanManager();
           mScanManager.openScanner();

           mScanManager.switchOutputMode( 0);
           soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
           soundid = soundpool.load("/etc/Scan_new.ogg", 1);
           //隐藏手机扫码
           scanButton.setVisibility(View.GONE);
       }catch (Exception e){
           scanButton.setVisibility(View.VISIBLE);
            Log.i(TAG,"手机初始化，没有mScanManager");
       }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if(mScanManager != null) {
            try{
                mScanManager.stopDecode();
            }catch (Exception e){

            }
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        try{//兼容手机，没有扫码头
            initScan();
        }catch (Exception e){

        }

//        scanInput.setText("");
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return super.onKeyDown(keyCode, event);
    }

}